#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
营销方案生成系统后端API
集成MongoDB数据库，支持完整的需求和方案管理
"""

import os
from datetime import datetime
from flask import Flask, request, jsonify
from flask_cors import CORS
import logging
from pymongo import MongoClient
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 导入模型和路由
from models import RequirementModel, SolutionModel
from config import config
from routes import create_routes

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 创建Flask应用
app = Flask(__name__)
app.config.from_object(config['development'])

# 配置CORS
CORS(app, origins=app.config['CORS_ORIGINS'])

# 注册蓝图（在数据库连接成功后）

# MongoDB连接
try:
    mongo_uri = os.getenv('MONGO_URI', 'mongodb://localhost:27017/')
    database_name = os.getenv('DATABASE_NAME', 'marketiq_ai')
    
    client = MongoClient(mongo_uri)
    db = client[database_name]
    
    # 测试连接
    client.admin.command('ping')
    logger.info(f'MongoDB连接成功: {database_name}')
    
    # 初始化模型
    requirement_model = RequirementModel(db)
    solution_model = SolutionModel(db)
    
    # 注册蓝图
    api_blueprint = create_routes(db)
    app.register_blueprint(api_blueprint)
    
except Exception as e:
    logger.error(f'MongoDB连接失败: {str(e)}')
    raise

# API路由

@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    try:
        # 测试数据库连接
        client.admin.command('ping')
        return jsonify({
            'status': 'healthy',
            'database': 'connected',
            'timestamp': datetime.now().isoformat()
        }), 200
    except Exception as e:
        logger.error(f'健康检查失败: {str(e)}')
        return jsonify({
            'status': 'unhealthy',
            'database': 'disconnected',
            'error': str(e),
            'timestamp': datetime.now().isoformat()
        }), 500


@app.route('/api/requirements', methods=['POST'])
def create_requirement():
    """创建营销需求"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({
                'status': 'error',
                'message': '请求数据不能为空'
            }), 400
        
        # 使用模型创建需求
        success, message, requirement = requirement_model.create(data)
        
        if success:
            logger.info(f'需求创建成功: {requirement["id"]}')
            return jsonify({
                'status': 'success',
                'message': message,
                'data': requirement
            }), 201
        else:
            return jsonify({
                'status': 'error',
                'message': message
            }), 400
            
    except Exception as e:
        logger.error(f'创建需求失败: {str(e)}')
        return jsonify({
            'status': 'error',
            'message': f'创建需求失败: {str(e)}'
        }), 500


@app.route('/api/requirements/<requirement_id>', methods=['GET'])
def get_requirement(requirement_id):
    """获取单个需求"""
    try:
        success, message, requirement = requirement_model.get_by_id(requirement_id)
        
        if success:
            return jsonify({
                'status': 'success',
                'data': requirement
            }), 200
        else:
            return jsonify({
                'status': 'error',
                'message': message
            }), 404
            
    except Exception as e:
        logger.error(f'获取需求失败: {str(e)}')
        return jsonify({
            'status': 'error',
            'message': f'获取需求失败: {str(e)}'
        }), 500


@app.route('/api/requirements', methods=['GET'])
def get_requirements():
    """获取需求列表"""
    try:
        # 获取查询参数
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 10))
        status = request.args.get('status')
        
        success, message, result = requirement_model.list(page, limit, status)
        
        if success:
            return jsonify({
                'status': 'success',
                'data': result
            }), 200
        else:
            return jsonify({
                'status': 'error',
                'message': message
            }), 500
            
    except Exception as e:
        logger.error(f'获取需求列表失败: {str(e)}')
        return jsonify({
            'status': 'error',
            'message': f'获取需求列表失败: {str(e)}'
        }), 500


@app.route('/api/requirements/<requirement_id>', methods=['PUT'])
def update_requirement(requirement_id):
    """更新需求"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({
                'status': 'error',
                'message': '请求数据不能为空'
            }), 400
        
        success, message, requirement = requirement_model.update(requirement_id, data)
        
        if success:
            logger.info(f'需求更新成功: {requirement_id}')
            return jsonify({
                'status': 'success',
                'message': message,
                'data': requirement
            }), 200
        else:
            return jsonify({
                'status': 'error',
                'message': message
            }), 400
            
    except Exception as e:
        logger.error(f'更新需求失败: {str(e)}')
        return jsonify({
            'status': 'error',
            'message': f'更新需求失败: {str(e)}'
        }), 500


@app.route('/api/requirements/<requirement_id>', methods=['DELETE'])
def delete_requirement(requirement_id):
    """删除需求"""
    try:
        success, message = requirement_model.delete(requirement_id)
        
        if success:
            logger.info(f'需求删除成功: {requirement_id}')
            return jsonify({
                'status': 'success',
                'message': message
            }), 200
        else:
            return jsonify({
                'status': 'error',
                'message': message
            }), 404
            
    except Exception as e:
        logger.error(f'删除需求失败: {str(e)}')
        return jsonify({
            'status': 'error',
            'message': f'删除需求失败: {str(e)}'
        }), 500


# 方案相关API
@app.route('/api/solutions', methods=['POST'])
def create_solution():
    """创建方案"""
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({
                'status': 'error',
                'message': '请求数据不能为空'
            }), 400
        
        success, message, solution = solution_model.create(data)
        
        if success:
            logger.info(f'方案创建成功: {solution["id"]}')
            return jsonify({
                'status': 'success',
                'message': message,
                'data': solution
            }), 201
        else:
            return jsonify({
                'status': 'error',
                'message': message
            }), 400
            
    except Exception as e:
        logger.error(f'创建方案失败: {str(e)}')
        return jsonify({
            'status': 'error',
            'message': f'创建方案失败: {str(e)}'
        }), 500


@app.route('/api/requirements/<requirement_id>/solutions/history', methods=['GET'])
def get_solution_history(requirement_id):
    """获取方案历史"""
    try:
        success, message, solutions = solution_model.get_history(requirement_id)
        
        if success:
            return jsonify({
                'status': 'success',
                'data': solutions
            }), 200
        else:
            return jsonify({
                'status': 'error',
                'message': message
            }), 404
            
    except Exception as e:
        logger.error(f'获取方案历史失败: {str(e)}')
        return jsonify({
            'status': 'error',
            'message': f'获取方案历史失败: {str(e)}'
        }), 500


@app.route('/api/requirements/<requirement_id>/solutions/latest', methods=['GET'])
def get_latest_solution(requirement_id):
    """获取最新方案"""
    try:
        success, message, solution = solution_model.get_latest(requirement_id)
        
        if success:
            return jsonify({
                'status': 'success',
                'data': solution
            }), 200
        else:
            return jsonify({
                'status': 'error',
                'message': message
            }), 404
            
    except Exception as e:
        logger.error(f'获取最新方案失败: {str(e)}')
        return jsonify({
            'status': 'error',
            'message': f'获取最新方案失败: {str(e)}'
        }), 500


@app.route('/api/solutions/<solution_id>/confirm', methods=['POST'])
def confirm_solution(solution_id):
    """确认方案"""
    try:
        success, message, solution = solution_model.confirm_solution(solution_id)
        
        if success:
            logger.info(f'方案确认成功: {solution_id}')
            return jsonify({
                'status': 'success',
                'message': message,
                'data': solution
            }), 200
        else:
            return jsonify({
                'status': 'error',
                'message': message
            }), 404
            
    except Exception as e:
        logger.error(f'确认方案失败: {str(e)}')
        return jsonify({
            'status': 'error',
            'message': f'确认方案失败: {str(e)}'
        }), 500


@app.route('/api/requirements/<requirement_id>/solutions/statistics', methods=['GET'])
def get_solution_statistics(requirement_id):
    """获取方案统计"""
    try:
        success, message, statistics = solution_model.get_statistics(requirement_id)
        
        if success:
            return jsonify({
                'status': 'success',
                'data': statistics
            }), 200
        else:
            return jsonify({
                'status': 'error',
                'message': message
            }), 404
            
    except Exception as e:
        logger.error(f'获取方案统计失败: {str(e)}')
        return jsonify({
            'status': 'error',
            'message': f'获取方案统计失败: {str(e)}'
        }), 500


# 错误处理
@app.errorhandler(400)
def bad_request(error):
    """400错误处理"""
    return jsonify({
        'status': 'error',
        'message': '请求参数错误',
        'code': 400
    }), 400


@app.errorhandler(404)
def not_found(error):
    """404错误处理"""
    return jsonify({
        'status': 'error',
        'message': '请求的资源不存在',
        'code': 404
    }), 404


@app.errorhandler(500)
def internal_error(error):
    """500错误处理"""
    logger.error(f'服务器内部错误: {str(error)}')
    return jsonify({
        'status': 'error',
        'message': '服务器内部错误',
        'code': 500
    }), 500


if __name__ == '__main__':
    # 打印可用的API端点
    print("\n=== MarketIQ AI 营销方案生成系统 ===")
    print("可用的API端点:")
    print("- GET  /api/health                                    - 健康检查")
    print("- POST /api/requirements                              - 创建营销需求")
    print("- GET  /api/requirements/<id>                         - 获取单个需求")
    print("- GET  /api/requirements                              - 获取需求列表")
    print("- PUT  /api/requirements/<id>                         - 更新需求")
    print("- DELETE /api/requirements/<id>                       - 删除需求")
    print("- POST /api/solutions                                 - 创建方案")
    print("- GET  /api/requirements/<id>/solutions/history       - 获取方案历史")
    print("- GET  /api/requirements/<id>/solutions/latest        - 获取最新方案")
    print("- POST /api/solutions/<id>/confirm                    - 确认方案")
    print("- GET  /api/requirements/<id>/solutions/statistics    - 获取方案统计")
    print(f"\n服务器启动在: http://localhost:{app.config.get('PORT', 5001)}")
    print("="*50)
    
    # 启动应用
    app.run(
        host=app.config.get('HOST', '0.0.0.0'),
        port=app.config.get('PORT', 5001),
        debug=app.config.get('DEBUG', True)
    )